import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { CustomerSourceSelector as CustomerSourceSelect } from '@/components/business/customer'
import { CustomerGradeSelector as CustomerGradeSelect } from '@/components/business/customer'
import { CustomerStatusSelector as CustomerStatusSelect } from '@/components/business/customer'
import { RegionCascader } from '@/components/business/region'
import { AdminSelector, UserDepartmentSelector } from '@/components/business/user'
import { customerApi } from '@/api/customer'
import type {
  Customer,
  CustomerContact,
  CustomerTrace,
  CustomerChance,
  CustomerLog,
} from '@/types/customer'
import type { ApiResponse } from '@/types/api'

// 表单引用
const formRef = ref()

// 客户表单数据
const customerForm = reactive({
  id: '',
  customer_type: 16, // 默认企业客户
  name: '',
  source_id: '',
  tax_num: '',
  provinceid: '',
  cityid: '',
  distid: '',
  address: '',
  customer_status: '',
  grade_id: '',
  belong_name: '', // 管家姓名
  belong_uid: '', // 管家ID
  belong_did: '', // 管家部门ID
  belong_department: '', // 管家部门名称
  creator_name: '', // 录入人姓名
  creator_id: '', // 录入人ID
  share_names: '',
  share_uids: '',
  contact_name: '',
  contact_mobile: '',
  contact_email: '',
  contact_wechat: '',
  contact_qq: '',
  contact_gender: 1, // 1:男, 2:女
  description: '',
  group_code: '', // 客户分组代码
  is_primary: 0, // 是否主客户(0:否, 1:是)
  controller_name: '', // 负责人姓名
  relation_desc: '', // 客户关系描述
})

// 主客户名称
const primaryCustomerName = ref('')

// 主客户选择器弹窗可见性
const primaryCustomerSelectorVisible = ref(false)

// 地区级联数据 - 改为 string 类型以适配新组件
const regionData = ref<string>('')

// 处理地区选择变化
const handleRegionChange = (
  value: string | number | (string | number)[] | null,
  selectedOptions: any[]
) => {
  // 处理地区选择变化
  if (value) {
    // 如果是string类型，转换为数组格式
    if (typeof value === 'string') {
      const parts = value
        .split('/')
        .map(part => parseInt(part, 10))
        .filter(num => !isNaN(num))
      // 更新表单数据
      if (parts.length >= 1) customerForm.provinceid = parts[0].toString()
      if (parts.length >= 2) customerForm.cityid = parts[1].toString()
      if (parts.length >= 3) customerForm.distid = parts[2].toString()
    } else if (Array.isArray(value)) {
      // 数组类型
      if (value.length >= 1) customerForm.provinceid = value[0].toString()
      if (value.length >= 2) customerForm.cityid = value[1].toString()
      if (value.length >= 3) customerForm.distid = value[2].toString()
    } else if (selectedOptions && selectedOptions.length > 0) {
      // 使用selectedOptions获取省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      customerForm.provinceid = province?.id || ''
      customerForm.cityid = city?.id || ''
      customerForm.distid = district?.id || ''
    }
  } else {
    customerForm.provinceid = ''
    customerForm.cityid = ''
    customerForm.distid = ''
  }
}

// 监听地区数据变化
watch(
  () => [customerForm.provinceid, customerForm.cityid, customerForm.distid],
  ([provinceid, cityid, distid]) => {
    // 如果有完整的省市区数据，则更新regionData
    if (provinceid && cityid && distid) {
      // 新组件需要完整的路径字符串，格式为 "省份代码/城市代码/区县代码"
      regionData.value = `${provinceid}/${cityid}/${distid}`
    } else if (provinceid && cityid) {
      regionData.value = `${provinceid}/${cityid}`
    } else if (provinceid) {
      regionData.value = provinceid
    } else {
      regionData.value = ''
    }
  },
  { immediate: true }
)

// 初始化表单数据
const initFormData = (customer: any) => {
  Object.assign(customerForm, {
    id: customer.id,
    customer_type: customer.customer_type || 16,
    name: customer.name || '',
    source_id: customer.source_id || '',
    tax_num: customer.tax_num || '',
    provinceid: customer.provinceid || '',
    cityid: customer.cityid || '',
    distid: customer.distid || '',
    address: customer.address || '',
    customer_status: customer.customer_status || '',
    grade_id: customer.grade_id || '',
    belong_name: customer.belong_name || '',
    belong_uid: customer.belong_uid || '',
    belong_did: customer.belong_did || '',
    belong_department: customer.belong_department || '',
    // 增强录入人信息处理，支持多种可能的数据结构
    creator_name:
      customer.creator_name ||
      (customer.creator && customer.creator.name) ||
      customer.create_by_name ||
      '',
    creator_id:
      customer.creator_id ||
      (customer.creator && customer.creator.id) ||
      customer.create_by_id ||
      customer.admin_id ||
      '',
    share_names: customer.share_names || '',
    share_uids: customer.share_uids || '',
    contact_name: customer.contact_name || '',
    contact_mobile: customer.contact_mobile || '',
    contact_email: customer.contact_email || '',
    contact_wechat: customer.contact_wechat || '',
    contact_qq: customer.contact_qq || '',
    contact_gender: customer.contact_gender || 1,
    description: customer.description || '',
    group_code: customer.group_code || '',
    is_primary: customer.is_primary || 0,
    controller_name: customer.controller_name || '',
    relation_desc: customer.relation_desc || '',
  })

  // 设置地区数据为字符串格式
  if (customer.provinceid) {
    if (customer.cityid) {
      if (customer.distid) {
        regionData.value = `${customer.provinceid}/${customer.cityid}/${customer.distid}`
      } else {
        regionData.value = `${customer.provinceid}/${customer.cityid}`
      }
    } else {
      regionData.value = customer.provinceid
    }
  } else {
    regionData.value = ''
  }

  // 处理地区数据变化
  setTimeout(() => {
    // 触发watch监听，加载对应的城市和区县数据
    handleRegionChange(regionData.value, [])
  }, 100)

  // 如果不是主客户，需要加载主客户名称
  if (customer.is_primary === 0 && customer.group_code) {
    // 这里可以根据实际需求实现加载主客户名称的逻辑
    // 目前简单设置为与group_code相同
    primaryCustomerName.value = customerForm.name
  }
}

// 监听管家ID变化
watch(
  () => customerForm.belong_uid,
  newValue => {
    if (newValue && adminList.value.length > 0) {
      // 当管家ID改变时，更新管家相关信息
      const selectedAdmin = adminList.value.find(admin => String(admin.id) === String(newValue))
      if (selectedAdmin) {
        console.log('选中的管家信息:', selectedAdmin)
        customerForm.belong_name = selectedAdmin.name || ''
        if (selectedAdmin.department) customerForm.belong_department = selectedAdmin.department
        if (selectedAdmin.did) customerForm.belong_did = selectedAdmin.did
      } else {
        console.warn('未找到匹配的管家信息，ID:', newValue)
      }
    } else if (!newValue) {
      // 清空管家相关字段
      customerForm.belong_name = ''
      customerForm.belong_department = ''
      customerForm.belong_did = ''
    }
  }
)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  source_id: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  tax_num: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
  grade_id: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  contact_name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contact_mobile: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  contact_email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
}

// 用户列表
const userList = ref<any[]>([])

// 用户选择弹窗可见性
const userDialogVisible = ref(false)

// 管理员列表数据
const adminList = ref<any[]>([])

// 用户选择弹窗可见性
const userSelectorVisible = ref(false)

// 是否在选择录入人
const isSelectingCreator = ref(false)

// 返回上一页 - 由抽屉控件直接处理
const goBack = (emit: any) => {
  emit('cancel')
}

// 选择录入人
const selectCreator = () => {
  isSelectingCreator.value = true
  userSelectorVisible.value = true
}

// 选择管家
const selectUser = () => {
  isSelectingCreator.value = false
  userSelectorVisible.value = true
}

// 选择共享员工
const selectSharedUsers = () => {
  // 实现共享员工选择逻辑
  ElMessage.info('选择共享员工功能待实现')
}

// 处理是否主客户的变更
const handlePrimaryChange = (value: number) => {
  if (value === 1) {
    // 选择是主客户，清空主客户信息和group_code
    primaryCustomerName.value = ''
    customerForm.group_code = ''
  }
}

// 打开主客户选择器
const openPrimaryCustomerSelector = () => {
  primaryCustomerSelectorVisible.value = true
}

// 处理主客户选择
const handlePrimaryCustomerSelect = (customer: any) => {
  primaryCustomerName.value = customer.name
  customerForm.group_code = customer.group_code
}

// 处理用户选择完成
const handleUserSelected = (user: any) => {
  if (isSelectingCreator.value) {
    // 设置为录入人 - 始终使用name字段
    customerForm.creator_name = user.name
    customerForm.creator_id = user.id
  } else {
    // 设置为管家
    customerForm.belong_name = user.name
    customerForm.belong_uid = user.id
    customerForm.belong_did = user.did
    customerForm.belong_department = user.department
  }
}

// 提交表单
const submitForm = (emit: any) => {
  if (!formRef.value) return

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 创建提交数据副本，确保格式正确
        const submitData = {
          ...customerForm,
          // 将平铺的联系人信息转换为后端期望的contacts数组格式
          contacts: [
            {
              name: customerForm.contact_name || '',
              mobile: customerForm.contact_mobile || '',
              email: customerForm.contact_email || '',
              wechat: customerForm.contact_wechat || '',
              qq: customerForm.contact_qq || '',
              gender: customerForm.contact_gender || 1,
            },
          ],
        }

        console.log('提交客户数据:', submitData)
        // 调用customerApi的editCustomer方法提交数据
        const response = await customerApi.editCustomer(submitData)

        if (response.data.code === 0) {
          ElMessage.success('更新客户成功')
          emit('submit', customerForm)
        } else {
          ElMessage.error(response.msg || '更新客户失败')
        }
      } catch (error) {
        console.error('提交客户数据失败:', error)
        ElMessage.error((error as Error).message || '更新客户失败')
      }
    }
  })
}

// 客户来源选项
const sourceOptions = ref<any[]>([])

// 客户等级选项
const gradeOptions = ref<any[]>([])

// 客户状态选项
const statusOptions = ref<any[]>([])

// 加载客户来源选项
const loadSourceOptions = async () => {
  try {
    const response = await customerApi.getSourceOptions()
    if (response.code === 0 && Array.isArray(response.data)) {
      sourceOptions.value = response.data
    } else {
      console.error('获取客户来源选项失败')
    }
  } catch (error) {
    // 只处理非取消请求的错误
    if (error && (error as any).code !== 'ERR_CANCELED') {
      console.error('获取客户来源选项异常:', error)
    }
  }
}

// 加载客户等级选项
const loadGradeOptions = async () => {
  try {
    const response = await customerApi.getCustomerGradeOptions()
    if (response.code === 0 && Array.isArray(response.data)) {
      gradeOptions.value = response.data
    } else {
      console.error('获取客户等级选项失败')
    }
  } catch (error) {
    // 只处理非取消请求的错误
    if (error && (error as any).code !== 'ERR_CANCELED') {
      console.error('获取客户等级选项异常:', error)
    }
  }
}

// 加载客户状态选项
const loadStatusOptions = async () => {
  try {
    const response = await customerApi.getCustomerStatusOptions()
    if (response.code === 0 && Array.isArray(response.data)) {
      statusOptions.value = response.data
    } else {
      console.error('获取客户状态选项失败')
    }
  } catch (error) {
    // 只处理非取消请求的错误
    if (error && (error as any).code !== 'ERR_CANCELED') {
      console.error('获取客户状态选项异常:', error)
    }
  }
}

// 初始化数据
const init = async (customerId: string) => {
  if (!customerId) {
    ElMessage.error('客户ID不能为空')
    return
  }

  try {
    // 先并行加载选项数据，确保在初始化表单前准备好
    await Promise.allSettled([
      loadAdminList(),
      loadSourceOptions(),
      loadGradeOptions(),
      loadStatusOptions(),
    ])

    // 然后再获取客户详情并初始化表单
    const customerResponse = await customerApi.viewCustomer({ id: customerId })

    // 处理客户详情
    if (customerResponse && (customerResponse as any).code === 0) {
      const customerData = customerResponse.data
      // 初始化表单数据
      initFormData(customerData)

      // 为了确保录入人信息正确显示，进行额外检查
      if (!customerForm.creator_name || !customerForm.creator_id) {
        // 检查可能的其他数据结构
        const creatorInfo = customerData.creator || {}
        if (creatorInfo && creatorInfo.name) {
          customerForm.creator_name = creatorInfo.name
          customerForm.creator_id = (creatorInfo.id || creatorInfo.uid || '').toString()
        }
        // 额外检查admin_id字段
        if (!customerForm.creator_id && customerData.admin_id) {
          customerForm.creator_id = customerData.admin_id.toString()
          // 尝试根据admin_id从管理员列表中查找对应的名字
          if (adminList.value && adminList.value.length > 0) {
            // 增强类型处理，确保能够正确匹配
            const adminIdStr = String(customerData.admin_id)
            const adminInfo = adminList.value.find(admin => String(admin.id) === adminIdStr)
            if (adminInfo && adminInfo.name) {
              customerForm.creator_name = adminInfo.name
            } else {
              // 当找不到对应管理员时，提供一个默认名称
              customerForm.creator_name = `管理员${adminIdStr}`
            }
          } else {
            // 当管理员列表为空时，也提供默认名称
            customerForm.creator_name = `管理员${customerData.admin_id}`
          }
        }
      }
    } else {
      ElMessage.error((customerResponse as any)?.msg || '获取客户详情失败')
    }
  } catch (error) {
    // 只处理非取消请求的错误
    if (error && (error as any).code !== 'ERR_CANCELED') {
      console.error('初始化数据失败:', error)
      ElMessage.error((error as Error).message || '初始化数据失败')
    }
  }
}

// 加载管理员列表
const loadAdminList = async () => {
  try {
    const response = await customerApi.getAdminList()
    if (response && (response as any).code === 0) {
      adminList.value = response.data || []
    }
  } catch (error) {
    // 只处理非取消请求的错误
    if (error && (error as any).code !== 'ERR_CANCELED') {
      console.error('获取管理员列表失败:', error)
    }
  }
}

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  formRef,
  customerForm,
  regionData,
  rules,
  userList,
  userDialogVisible,
  adminList,
  userSelectorVisible,
  isSelectingCreator,
  sourceOptions,
  gradeOptions,
  statusOptions,
  primaryCustomerName,
  primaryCustomerSelectorVisible,

  // 方法
  goBack,
  selectCreator,
  selectUser,
  selectSharedUsers,
  handleUserSelected,
  submitForm,
  init,
  initFormData,
  handleRegionChange,
  handlePrimaryChange,
  openPrimaryCustomerSelector,
  handlePrimaryCustomerSelect,
}
